import { forwardRef, useImperativeHandle, useRef, memo } from 'react'
import { useSelector } from 'react-redux'
import Uppy from '@uppy/core'
import { Dashboard } from '@uppy/react'
import ImageEditor from '@uppy/image-editor'
import propTypes from 'prop-types'
import '@uppy/core/dist/style.css'
import '@uppy/dashboard/dist/style.css'
import '@uppy/image-editor/dist/style.css'
// import { useEffect } from 'react'

const CropperImgUppy = forwardRef(function CropperImgUppy(props, ref) {
  const { onBeforeUpload, onBeforeFileAdd } = props
  
  const theme = useSelector(state => state.auth.theme)

  const CropperDomRef = useRef(null)
  // const [currentImg, setCurrentImg] = useState('')

  const uppy = new Uppy({
    restrictions: {
      maxNumberOfFiles: 1,
      allowedFileTypes: ['image/*', '.jpg', '.jpeg', '.png', '.gif']
    },
    onBeforeFileAdded: (currentFile) => {
      if (onBeforeFileAdd && typeof (onBeforeFileAdd) === 'function') {
        onBeforeFileAdd(currentFile)
      }
    },
    onBeforeUpload: (Files) => {
      if (onBeforeUpload && typeof (onBeforeUpload) === 'function') {
        onBeforeUpload(Files)
      }
      return false
    }
  })
  uppy.use(ImageEditor, {
    quality: 0.8,
  })

  useImperativeHandle(ref, () => ({
    removeAllFiles: () => {
      const currentFiles = uppy.getFiles()
      currentFiles.forEach(file => {
        uppy.removeFile(file.id)
      })
    },
    domRef: CropperDomRef.current
  }))

  return (
    <div className="Cropper-img-tools" ref={CropperDomRef}>
      <Dashboard
        uppy={uppy}
        plugins={['ImageEditor']}
        theme={theme === 'dark' ? 'dark' : 'light'}
        proudlyDisplayPoweredByUppy={false}
        locale={{
          strings: {
            myDevice: '此设备',
            dropPasteFiles: '把文件拖到这进行上传'
          }
        }}
      />
    </div>
  )
})

CropperImgUppy.propTypes = {
  onBeforeUpload: propTypes.func.isRequired
}

export default memo(CropperImgUppy)